<?php
/**
 * UserController Controller Class File
 *
 * @package
 * @author
 */

Yii::import('application.models.AuthAssignment');

/**
 * UserController Class
 *
 * @package
 * @author
 */
class UserController extends MyController
{
    // {{{ *** Members ***

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    // public $layout='//layouts/column2';

    
    /**
     * The default action 
     * 
     * @var string
     */
    public $defaultAction = 'admin';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    public $name='Users';

    // }}} End Members
    // {{{ *** Methods ***
    // {{{ filters
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    } // }}} 
    // {{{ accessRules
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules()
    {
        return array();
    } // }}} 
    // {{{ *** Actions ***
    // {{{ actionView
    /**
     * Displays a particular model.
     */
    public function actionView()
    {
        $this->checkAccess('admin');

        $this->render('view',array(
            'model'=>$this->loadModel(),
        ));
    } // }}} 
    // {{{ actionCreate
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->checkAccess('admin');
        
        $model=new User();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            if($model->save()) {
                $this->setFlash( 'create', $model );
                $this->redirect(array('view','id'=>$model->id));
            }
        }

        $this->render('create',array('model'=>$model,));
    } // }}} 
    // {{{ actionUpdate
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate()
    {
        $this->checkAccess('admin');
        
        $model=$this->loadModel();
        $this->prepareDateFields($model);
        $this->prepareNumericFields($model);
        $model->password='';

        // Store old value for registration completed
        $regCompletedOld    = $model->registrationComplete;

        //echo "<li>Model->scenario: {$model->scenario}";

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        // {{{ Delete or add Auth Assignments?
        if(isset($_POST['AuthAssignment'])) {
            // DEBUG echo par($_POST['AuthAssignment']);
            // {{{ Delete Auth Assignments?
            if(isset($_POST['AuthAssignment']['delete']) and is_array($_POST['AuthAssignment']['delete'])) {
                $numDeleted=0;
                foreach($_POST['AuthAssignment']['delete'] as $itemNameUserId) {
                    list($itemname,$userid) = explode('|',$itemNameUserId);
                    Yii::log("Delete auth assignment $itemname for userid $userid");
                    if(AuthAssignment::model()->deleteAll(array('condition'=>"itemname='$itemname' AND userid=$userid"))>0) {
                        $numDeleted++;
                    }
                }
                Yii::app()->user->setFlash(
                    'success',
                    Yii::t('site','{numDeleted} Auth Assignments have been deleted.',array('{numDeleted}'=>$numDeleted))
                );
            }
            // }}} 
            // {{{ Add a new auth assignment?
            if(isset($_POST['AuthAssignment']['add']) and $_POST['AuthAssignment']['add']!=='') {
                $authAssignment = new AuthAssignment;
                $authAssignment->itemname = $_POST['AuthAssignment']['add'];
                $authAssignment->userid = $_GET['id'];
                if($authAssignment->save()) {
                    Yii::app()->user->setFlash(
                        'success',
                        Yii::t(
                            'site',
                            'The Auth Assignment {itemname} has been added.',
                            array('{itemname}'=>$_POST['AuthAssignment']['add'])
                        )
                    );
                }
            }
            // }}} 
        } // }}} 

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            // echo par($model->attributes, 'actionUpdate');
            $model->password2 = $_POST['User']['password2'];
            if($model->validate()) {
                if($regCompletedOld==0 and $model->registrationComplete==1) {
                    /*
                    $company = new CompanySetting;
                    $company->isVirgin = 1;
                    $company->userId = $model->id;
                    $company->invoiceNbrTemplate = Yii::app()->params['companyDefaults']['invoiceNbrTemplate'];
                    $company->receiptNbrTemplate = Yii::app()->params['companyDefaults']['receiptNbrTemplate'];
                    $company->save();
                    $model->companyId = $company->id;
                     */
                }
                if($model->save()) {
                    $this->setFlash( 'update', $model );
                    // Registration completed?
                    if($regCompletedOld==0 and $model->registrationComplete==1) {
                        // {{{ Send an email to the user
                        $to      = $model->email;
                        $subject = '['.Yii::app()->name.'] '.Yii::t('site','Registration Completed');
                        $app = Yii::app()->name;
                        $username = $model->username;
                        $link = Yii::app()->request->hostInfo.Yii::app()->createUrl('/site');
                        $message = $this->renderPartial('mailNewUser',array('app'=>$app,'link'=>$link,'username'=>$username),true);
                        $headers = 'From: '.Yii::app()->params['adminEmail']."\r\n" .
                            'Reply-To: '.Yii::app()->params['adminEmail']."\r\n" .
                            'X-Mailer: PHP/' . phpversion() .
                            'MIME-Version: 1.0' . "\r\n" .
                            'Content-Type: text/plain; charset="UTF-8"' . "\r\n";

                        mail($to, $subject, $message, $headers);
                        // }}} End send mail
                    }
                    $this->redirect(array('update','id'=>$model->id));
                }
            }
        }

        $this->render('update',array('model'=>$model,));
    } // }}} 
    // {{{ actionDelete
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete()
    {
        $this->checkAccess('admin');
        
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel()->delete();
            $this->setFlash( 'delete', $this->_model);

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,Yii::t('site','Invalid request. Please do not repeat this request again.'));
    } // }}} 
    // {{{ actionIndex
    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->checkAccess('admin');
        
        $dataProvider=new CActiveDataProvider('User');
        $this->render('index',array('dataProvider'=>$dataProvider,));
    } // }}} 
    // {{{ actionAdmin
    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $this->checkAccess('admin');
        
        $model=new User('search');
        // for clear-filters-gridview extension:
        if (intval(Yii::app()->request->getParam('clearFilters'))==1) {
            EButtonColumnWithClearFilters::clearFilters($this,$model);//where $this is the controller
        }
        /*
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['User']))
            $model->attributes=$_GET['User'];
        */
        $this->render('admin',array('model'=>$model,));
    } // }}} 
    // }}} End Actions
    // {{{ *** Other Methods
    // {{{ loadModel
    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if($this->_model===null)
        {
            if(isset($_GET['id']))
                $this->_model=User::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,Yii::t('site','The requested page does not exist.'));
        }
        return $this->_model;
    } // }}} 
    // {{{ performAjaxValidation
    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    // }}}
    // }}} End Other Methods
    // }}} End Methods
}
/* vim:set ai sw=4 sts=4 et fdm=marker fdc=4: */
